<template>
  <el-dialog append-to-body class="common_dialog" custom-class="reset-dialog-width" :visible.sync="visible" :title="!queryParams.id ?'添加智能柜列表' : '修改智能柜列表'" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="form" :rules="dataRule" ref="form" label-width="120px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" :maxlength="20" placeholder="请输入名称（最多20个字）" clearable />
      </el-form-item>
      <el-form-item label="所在城市" prop="city">
        <el-select v-model="form.city" placeholder="请选择所在城市" clearable @change="changeCity">
          <el-option v-for="item in cityList" :key="item.id" :label="item.mergename" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所在区域" prop="regionId">
        <el-select v-model="form.regionId" placeholder="请选择所在区域" clearable :disabled="regionListDisabled">
          <el-option v-for="item in regionList" :key="item.id" :label="item.details" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <!-- {{form.address}} -->
      <el-form-item label="请选择经纬度" prop="address" class="input_btn">
        <el-input v-model="form.address" disabled placeholder="请选择经纬度">
          <el-button slot="suffix" type="primary" @click="addressHandle">请选择经纬度</el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="详细地址" prop="addressDetail">
        <el-input v-model="form.addressDetail" placeholder="请输入详细地址" clearable />
      </el-form-item>
      <el-form-item label="柜子总和" prop="numCount">
        <el-input type="number" v-model="form.numCount" @change="changeNumCount" placeholder="请输入柜子总和" clearable />
      </el-form-item>
      <el-form-item label="柜子门总数" prop="maxCount">
        <el-input type="number" v-model="form.maxCount" placeholder="请输入柜子门总数" clearable />
      </el-form-item>
      <el-form-item label="板子信息" prop="ban">
        <el-input v-model="form.ban" placeholder="请输入板子信息" clearable />
      </el-form-item>
      <el-form-item label="柜组编号" prop="cabinetGroupNo">
        <el-select v-model="form.cabinetGroupNo" filterable remote reserve-keyword placeholder="请输入柜组编号" :remote-method="remoteMethod" :loading="loading">
          <el-option v-for="item in cabinetGroupNoOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

    </el-form>
    <template slot="footer">
      <el-button :loading="confirmLoading" type="primary" @click="formSubmitHandle()">确 定</el-button>
      <el-button @click="visible = false">取 消</el-button>
    </template>
    <!-- 弹窗, 选择经纬度 -->
    <choose-address v-if="mapShow" ref="chooseAddress" @refreshAddressPosition="getAddressPosition"></choose-address>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import { addSmartCabinet, getSmartCabinet, updateSmartCabinet } from "@/api/smartCabinet/smartCabinet";
import { findInRegionList } from "@/api/basic/area/area";
import { findRegionByAreaId } from "@/api/basic/region/region";
import { cabinetGroupGetAll } from "@/api/deliver/cabinetGroup";
import ChooseAddress from './choose-address'
export default {
  data() {
    return {
      visible: false,
      form: {
        seriesNo: '',
        name: '',
        city: '',
        regionId: '',
        position: '',
        lng: '',
        lat: '',
        addressDetail: '',
        address: '',
        numCount: null,
        maxCount: null,
        ban: '',
        cabinetGroupNo: '',
      },
      confirmLoading: false,
      queryParams: {},
      mapShow: false, // 地图显示
      regionListDisabled: true,
      cityList: [],//城市列表
      regionList: [], //区域列表
      loading: false, //柜组搜索加载
      cabinetGroupNoList: [], //柜组列表
      cabinetGroupNoOptions: [], //柜组编号option
    }
  },
  components: {
    ChooseAddress
  },
  computed: {
    dataRule() {
      return {
        city: [
          { required: true, message: '请选择所在城市', trigger: 'change' }
        ],
        regionId: [
          { required: true, message: '请选择区域', trigger: 'change' }
        ],
        address: [
          { required: true, message: '请选择经纬度', trigger: 'change' }
        ],
        cabinetGroupNo: [
          { required: true, message: '填写柜组', trigger: 'change' }
        ],
        name: [
          { required: true, message: '填写名称', trigger: 'change' }
        ],
        addressDetail: [
          { required: true, message: '填写详细地址', trigger: 'change' }
        ],
        numCount: [
          { required: true, message: '填写柜子总和', trigger: 'change' }
        ],
        maxCount: [
          { required: true, message: '填写柜子门总数', trigger: 'change' }
        ],
        ban: [
          { required: true, message: '填写板子信息', trigger: 'change' }
        ],
      }

    }
  },
  methods: {
    init() {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['form'].resetFields()
        this.reset()
        this.confirmLoading = false
        this.form.id = this.queryParams.id ? this.queryParams.id : ''
        this.cabinetGroupNoList = []
        findInRegionList().then(response => {
          this.cityList = response.data
        })
        cabinetGroupGetAll().then((res) => {
          res.data.map((item)=>{
            this.cabinetGroupNoList.push({
              value:`${item.cabinetGroupNo}`,
              label:`${item.cabinetGroupNo}`,
            })
          })
          
        })
        this.queryParams.id ? this.getInfo() : ''
      })
    },
    // 重置表单
    reset() {
      this.form = {
        id: null,
        seriesNo: '',
        name: '',
        city: '',
        regionId: '',
        position: '',
        lng: '',
        lat: '',
        addressDetail: '',
        address: '',
        numCount: null,
        maxCount: null,
        ban: '',
        cabinetGroupNo: '',
      };
    },
    // 获取信息
    getInfo() {
      const id = this.queryParams.id
      getSmartCabinet(id).then(response => {
        response.data.city = response.data.city ? Number(response.data.city) : ''
        this.getFindRegionByAreaId(response.data.city)
        this.form = response.data;
      });
    },
    // 柜组编号远程搜索方法
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.cabinetGroupNoOptions = this.cabinetGroupNoList.filter(item => {
            return item.label.toLowerCase()
              .indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this.cabinetGroupNoOptions = [];
      }
  },
  // 点击获取经纬度
  addressHandle() {
    this.mapShow = true
    this.$nextTick(() => {
      this.$refs.chooseAddress.init()
      this.$refs.chooseAddress.centerMarker = this.form.lng ? [this.form.lng, this.form.lat] : [119.542197, 39.943673]
      this.$refs.chooseAddress.address = this.form.address ? this.form.address : '河北省洁客科技有限公司'
    })
  },
  // 获取定位坐标
  getAddressPosition(position, address) {
    this.form.lat = position.lat
    this.form.lng = position.lng
    this.form.address = address
  },
  // 选择城市，城市改变后执行
  changeCity(value) {
    if (this.form.city) {
      //切换的时候城市清空，防止bug
      this.form.regionId = ''
      this.regionList = [];
      this.regionListDisabled = false;
      this.getFindRegionByAreaId(this.form.city)
    } else {
      this.regionList = [];
      this.regionListDisabled = true;
    }
  },
  // 获取区域列表
  getFindRegionByAreaId(id) {
    id ? findRegionByAreaId(id).then(response => {
      this.regionList = response.data
    }) : '';
  },
  // 输入柜子总和后柜子门总数*24
  changeNumCount() {
    this.form.maxCount = this.form.numCount * 24
  },
  // 表单提交
  formSubmitHandle: debounce(function () {
    this.$refs["form"].validate(valid => {
      if (valid) {
        this.confirmLoading = true
        if (this.form.id != '') {
          this.form.maintainflag = false
          updateSmartCabinet(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.visible = false
            this.confirmLoading = false
            this.$emit('refreshDataList')
          }).catch(() => {
            this.confirmLoading = false
          });
        } else {
          addSmartCabinet(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.visible = false
            this.confirmLoading = false
            this.$emit('refreshDataList')
          }).catch(() => {
            this.confirmLoading = false
          });
        }
      }
    })
  }, 1000, { 'leading': true, 'trailing': false }),

}
}
</script>
<style lang="scss" scoped>
</style>
